package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.dto.ThirdInfoDTO;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.LogFactory;
import com.block.common.service.merchant.IMerchantThirdBaseInfoService;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.YangXinHuaAESUtil;
import com.block.datapush.service.apipush.utils.YangXinHuaApibUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.mapper.MerchantThirdBaseInfoMapper;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * 安易融  双授权
 */
@Service
public class YangXinHuaApisPushApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMerchantThirdBaseInfoService merchantThirdBaseInfoService;
    @Autowired
    IApplicationInfoService applicationInfoService;
    @Autowired
    MerchantThirdBaseInfoMapper merchantThirdBaseInfoMapper;

    String timeStamp = String.valueOf(System.currentTimeMillis());
    String requestId = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        String queryUrl = pushApiKeyParam.getCheckUrl();
        String mobileMd5 = memberSourceInfo.getMobileMd5().toLowerCase();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("phoneMd5", mobileMd5);
        paramMap.put("name",memberSourceInfo.getRealname());
        paramMap.put("sex",memberSourceInfo.getSex()==1?"男":"女");
        paramMap.put("age",memberSourceInfo.getAge());
        paramMap.put("cityCode",memberSourceInfo.getCityCode());
        paramMap.put("loanAmt", YangXinHuaApibUtil.getLoanAmount(memberSourceInfo.getLoanAmount()));
        paramMap.put("loanTerm", YangXinHuaApibUtil.getLoanTerm(memberSourceInfo.getLoanTime()));
        paramMap.put("loanUse",YangXinHuaApibUtil.getYongTu(memberSourceInfo.getYongtu()));
        paramMap.put("education", YangXinHuaApibUtil.getXueli(memberSourceInfo.getXueli()));
        paramMap.put("car", YangXinHuaApibUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("house", YangXinHuaApibUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("social", YangXinHuaApibUtil.getShebao(memberSourceInfo.getShebao()));
        paramMap.put("fund", YangXinHuaApibUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("insurance", YangXinHuaApibUtil.getBaoxian(memberSourceInfo.getBaoxian()));
        paramMap.put("zhima", YangXinHuaApibUtil.getZhima(memberSourceInfo.getZhima()));
        paramMap.put("huabei", YangXinHuaApibUtil.getHuaBei(memberSourceInfo.getHuabei()));
        paramMap.put("baitiao", YangXinHuaApibUtil.getBaiTiao(memberSourceInfo.getBaitiao()));
        paramMap.put("creditStatus", YangXinHuaApibUtil.getYuqi(memberSourceInfo.getYuqi()));
        paramMap.put("profession", YangXinHuaApibUtil.getJob(memberSourceInfo.getGongzuo()));
        String job = YangXinHuaApibUtil.getJob(memberSourceInfo.getGongzuo());
        if(StrUtil.equals(job,"4")){
            paramMap.put("license", "1");
        }
        if(StrUtil.equals(job,"2")){
            paramMap.put("monthIncome", YangXinHuaApibUtil.getShouru(memberSourceInfo.getShouru()));
            paramMap.put("salaryType","1");
        }
        paramMap.put("ip", memberSourceInfo.getReqIp());
        paramMap.put("platform", "ANDROID");
        paramMap.put("timeStamp",timeStamp);
        Map<String, String> map = new HashMap<>();
        map.put("requestId", requestId);
        map.put("timeStamp", timeStamp);
        map.put("phoneMd5", mobileMd5);
        paramMap.put("sign", sign(convertMap2String(map), pushApiKeyParam.getApiSecret()));
        String encrypt = YangXinHuaAESUtil.encryptAESECB(JSON.toJSONString(paramMap), pushApiKeyParam.getApiKey());
        Map<String,Object> aceMap = new HashMap<>();
        aceMap.put("requestId",requestId);
        aceMap.put("channelCode",pushApiKeyParam.getApiCode());
        aceMap.put("data",encrypt);

        log.info("【阳薪花全流程】撞库开始【queryUrl】{}【paramMap】{} 【aceMap】{}", queryUrl, JSON.toJSONString(paramMap),JSON.toJSONString(aceMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(aceMap))
                .execute().body();
        JSONObject resultObject = JSON.parseObject(result);

        log.info("【阳薪花全流程】撞库结束【resultDes】{}", resultObject.toJSONString());

        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("message");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (code == 200) {
            JSONObject data = resultObject.getJSONObject("data");
            JSONObject orgInfo = data.getJSONObject("orgInfo");
            String productName = orgInfo.getString("productName");
            String loanName = orgInfo.getString("productOrgName");
            String productIcon = orgInfo.getString("productIcon");
            // 撞库成功之后，商户的机构数据存储

            ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
            thirdInfoDTO.setInfoId(Integer.valueOf(pushApiKeyParam.getInfoId()));
            thirdInfoDTO.setInfoName(pushApiKeyParam.getInfoName());
            thirdInfoDTO.setOrderNo(orderNo);
            JSONObject infoObject = new JSONObject();
            infoObject.put("companyLogo",productIcon);
            infoObject.put("productName",productName);
            infoObject.put("companyName",loanName);
            infoObject.put("maxLoanAmount","200000");
            infoObject.put("maxLoanRate","20");
            infoObject.put("minLoanRate","1");
            infoObject.put("businessInfo",pushApiKeyParam.getInfoName());
            JSONArray jsonArray = new JSONArray();
            JSONArray agreements = data.getJSONArray("agreements");
            for (int i=0;i<agreements.size();i++){
                JSONObject jsonObject = new JSONObject();
                String agreemenName = agreements.getJSONObject(i).getString("name");
                String agreemenUrl = agreements.getJSONObject(i).getString("url");
                jsonObject.put("protocalName",agreemenName);
                jsonObject.put("protocalUrl",agreemenUrl);
                jsonArray.add(jsonObject);
            }
            infoObject.put("agreements",jsonArray);
            thirdInfoDTO.setInfoObject(infoObject);

            //进行分润操作
            String priceType = pushApiKeyParam.getPriceType();
            BigDecimal typeRate = pushApiKeyParam.getTypeRate();
            if (ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)){
                BigDecimal price = data.getBigDecimal("price");//下游返回分润后价格
                if (price.compareTo(new BigDecimal(0.00)) == -1){
                    pushApiResult.setPushSuccess(false);
                    return pushApiResult;
                }
                BigDecimal priceLeft = price.divide(typeRate);//分润前价格
                pushApiResult.setPrice(priceLeft);
                pushApiResult.setPriceRight(price);
            }

            boolean save = merchantThirdBaseInfoService.saveThirdInfo(thirdInfoDTO);
            if (save){
                pushApiResult.setPushSuccess(true);

            }else{
                pushApiResult.setMessage("保存撞库数据失败");
            }
        }
        return pushApiResult;
    }

    public static String sign(String contentString, String encryptKey) {
        contentString = contentString + encryptKey;
        String sign = DigestUtils.md5Hex(contentString);
        return sign;
    }

    public static String convertMap2String(Map<String, String> paramsMap) {
        StringBuffer content = new StringBuffer();
        List<String> keys = new ArrayList<>(paramsMap.keySet());
        Collections.sort(keys);
        int index = 0;
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = paramsMap.get(key);
            if (!key.isEmpty() && !value.isEmpty()) {
                content.append((index == 0 ? "" : "&") + key + "=" + value);
                index++;
            }
        }
        return content.toString();
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("phone", memberSourceInfo.getMobile());
        paramMap.put("name",memberSourceInfo.getRealname());
        paramMap.put("sex",memberSourceInfo.getSex()==1?"男":"女");
        paramMap.put("age",memberSourceInfo.getAge());
        paramMap.put("cityCode",memberSourceInfo.getCityCode());
        paramMap.put("loanAmt", YangXinHuaApibUtil.getLoanAmount(memberSourceInfo.getLoanAmount()));
        paramMap.put("loanTerm", YangXinHuaApibUtil.getLoanTerm(memberSourceInfo.getLoanTime()));
        paramMap.put("loanUse",YangXinHuaApibUtil.getYongTu(memberSourceInfo.getYongtu()));
        paramMap.put("education", YangXinHuaApibUtil.getXueli(memberSourceInfo.getXueli()));
        paramMap.put("car", YangXinHuaApibUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("house", YangXinHuaApibUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("social", YangXinHuaApibUtil.getShebao(memberSourceInfo.getShebao()));
        paramMap.put("fund", YangXinHuaApibUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("insurance", YangXinHuaApibUtil.getBaoxian(memberSourceInfo.getBaoxian()));
        paramMap.put("zhima", YangXinHuaApibUtil.getZhima(memberSourceInfo.getZhima()));
        paramMap.put("huabei", YangXinHuaApibUtil.getHuaBei(memberSourceInfo.getHuabei()));
        paramMap.put("baitiao", YangXinHuaApibUtil.getBaiTiao(memberSourceInfo.getBaitiao()));
        paramMap.put("creditStatus", YangXinHuaApibUtil.getYuqi(memberSourceInfo.getYuqi()));
        paramMap.put("profession", YangXinHuaApibUtil.getJob(memberSourceInfo.getGongzuo()));
        String job = YangXinHuaApibUtil.getJob(memberSourceInfo.getGongzuo());
        if(StrUtil.equals(job,"4")){
            paramMap.put("license", "1");
        }
        if(StrUtil.equals(job,"2")){
            paramMap.put("monthIncome", YangXinHuaApibUtil.getShouru(memberSourceInfo.getShouru()));
            paramMap.put("salaryType","1");
        }
        paramMap.put("ip", memberSourceInfo.getReqIp());
        paramMap.put("platform", "ANDROID");
        paramMap.put("timeStamp",timeStamp);
        Map<String, String> map = new HashMap<>();
        map.put("requestId", outOrderNo);
        map.put("timeStamp", timeStamp);
        map.put("phone", memberSourceInfo.getMobile());
        paramMap.put("sign", sign(convertMap2String(map), pushApiKeyParam.getApiSecret()));
        String encrypt = YangXinHuaAESUtil.encryptAESECB(JSON.toJSONString(paramMap), pushApiKeyParam.getApiKey());
        Map<String,Object> aceMap = new HashMap<>();
        aceMap.put("requestId",outOrderNo);
        aceMap.put("channelCode",pushApiKeyParam.getApiCode());
        aceMap.put("data",encrypt);

        log.info("【阳薪花全流程】导单开始【queryUrl】{}【bizMap】{}【paramMap】{}", requestUrl, JSON.toJSONString(paramMap), JSON.toJSONString(aceMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(aceMap))
                .execute().body();

        JSONObject resultObject = JSON.parseObject(result);

        log.info("【阳薪花全流程】导单结束【result】{}", resultObject.toJSONString());

        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("message");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setOrderNo(orderNo);
        thirdInfoDTO.setRetCode(String.valueOf(code));
        thirdInfoDTO.setRetMsg(msg);
        thirdInfoDTO.setResultInfo(result);
        thirdInfoDTO.setStatus("FAILED");

        if (code == 1){
            thirdInfoDTO.setStatus("SUCCESS");
        }
        merchantThirdBaseInfoService.updateThirdInfo(thirdInfoDTO);
        if (code == 1) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }

}
